package com.example.shuiyin.service;

import com.example.shuiyin.config.MinioConfig;
import io.minio.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
@RequiredArgsConstructor
@Slf4j
public class MinioConfigurer implements ApplicationListener<ApplicationReadyEvent> {

    private final MinioClient minioClient;
    private final MinioConfig minioConfig;

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        initializeMinioStorage();
    }

    public void initializeMinioStorage() {
        if (!minioConfig.isEnabled()) {
            log.info("MinIO 存储服务已禁用");
            return;
        }
        
        try {
            // 检查存储桶是否存在，不存在则创建
            boolean bucketExists = minioClient.bucketExists(BucketExistsArgs.builder()
                    .bucket(minioConfig.getBucket())
                    .build());
                    
            if (!bucketExists) {
                minioClient.makeBucket(MakeBucketArgs.builder()
                        .bucket(minioConfig.getBucket())
                        .build());
                
                // 设置存储桶为公共可读
                String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:GetObject\"],\"Resource\":[\"arn:aws:s3:::" + minioConfig.getBucket() + "/*\"]}]}";
                
                minioClient.setBucketPolicy(SetBucketPolicyArgs.builder()
                        .bucket(minioConfig.getBucket())
                        .config(policy)
                        .build());
                
                log.info("已创建存储桶 {} 并设置为公共可读", minioConfig.getBucket());
            }
            
            // 检查其他桶配置
            if (minioConfig.getBuckets() != null) {
                for (Map.Entry<String, String> entry : minioConfig.getBuckets().entrySet()) {
                    String bucketName = entry.getValue();
                    boolean exists = minioClient.bucketExists(BucketExistsArgs.builder()
                            .bucket(bucketName)
                            .build());
                            
                    if (!exists) {
                        minioClient.makeBucket(MakeBucketArgs.builder()
                                .bucket(bucketName)
                                .build());
                        
                        // 设置为公共可读
                        String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:GetObject\"],\"Resource\":[\"arn:aws:s3:::" + bucketName + "/*\"]}]}";
                        
                        minioClient.setBucketPolicy(SetBucketPolicyArgs.builder()
                                .bucket(bucketName)
                                .config(policy)
                                .build());
                        
                        log.info("已创建存储桶 {} 并设置为公共可读", bucketName);
                    }
                }
            }
        } catch (Exception e) {
            log.error("MinIO 初始化失败: {}", e.getMessage(), e);
        }
    }
} 